package com.libinyn.base.pms.serivce.impl.sys;


import com.libinyn.base.pms.common.utils.Constant;
import com.libinyn.base.pms.entity.sys.SysMenuEntity;
import com.libinyn.base.pms.mapper.sys.SysMenuMapper;
import com.libinyn.base.pms.serivce.impl.BaseServiceImpl;
import com.libinyn.base.pms.serivce.sys.SysMenuService;
import com.libinyn.base.pms.serivce.sys.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * 菜单管理实现
 * @fileName: SysMenuServiceImpl.java
 * @author: bin.li01
 * @date: 2017/12/10 15:48 
 * @version: v1.0.0
 */
@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenuEntity> implements SysMenuService {

	@Resource
	private SysMenuMapper sysMenuMapper;
	@Resource
	private SysUserService sysUserService;
	
	@Override
	public List<SysMenuEntity> queryListParentId(Long parentId, List<Long> menuIdList) {

		List<SysMenuEntity> menuList = queryListParentId(parentId);
		if(menuIdList == null){
			return menuList;
		}
		
		List<SysMenuEntity> userMenuList = new ArrayList<>();
		for(SysMenuEntity menu : menuList){
			if(menuIdList.contains(menu.getMenuId())){
				userMenuList.add(menu);
			}
		}
		return userMenuList;
	}

	@Override
	public List<SysMenuEntity> queryListParentId(Long parentId) {
		SysMenuEntity sysMenuEntity = new SysMenuEntity();
		sysMenuEntity.setParentId(parentId);
		return sysMenuMapper.select(sysMenuEntity);
	}

	@Override
	public List<SysMenuEntity> queryNotButtonList() {
		return sysMenuMapper.queryNotButtonList();
	}

	@Override
	public List<SysMenuEntity> getUserMenuList(Long userId) {
		//系统管理员，拥有最高权限
		if(userId == Constant.SUPER_ADMIN){
			return sysMenuMapper.selectAll();
		}
		
		//用户菜单列表
		List<Long> menuIdList = sysUserService.queryAllMenuId(userId);
		return getAllMenuList(menuIdList);
	}

	@Override
	public void deleteBatch(Long[] menuIds) {
		sysMenuMapper.deleteBatch(menuIds);
	}
	
	@Override
	public List<SysMenuEntity> queryUserList(Long userId) {
		return sysMenuMapper.queryUserList(userId);
	}

	/**
	 * 获取所有菜单列表
	 */
	private List<SysMenuEntity> getAllMenuList(List<Long> menuIdList){
		//查询根菜单列表，根目录的父ID为0
		List<SysMenuEntity> menuList = queryListParentId(0L, menuIdList);
		//递归获取子菜单
		getMenuTreeList(menuList, menuIdList);
		
		return menuList;
	}

	/**
	 * 递归查询多层级菜单
	 */
	private List<SysMenuEntity> getMenuTreeList(List<SysMenuEntity> menuList, List<Long> menuIdList){
		List<SysMenuEntity> subMenuList = new ArrayList<SysMenuEntity>();
		
		for(SysMenuEntity entity : menuList){
			if(entity.getType() == Constant.MenuType.CATALOG.getValue()){//目录
				entity.setList(getMenuTreeList(queryListParentId(entity.getMenuId(), menuIdList), menuIdList));
			}
			subMenuList.add(entity);
		}
		
		return subMenuList;
	}
}
